
#include "mt6816.h"

SpiRawData spiRawData = {0};
AngleData angleData = {0};
unsigned short * readQuickCALData = (unsigned short *)STOCKPILE_APP_CALI_ADDR;

unsigned short MT6816_SendAndRead16Bits(unsigned short data)
{
    unsigned short receive = 0x0000;

    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);

    HAL_SPI_TransmitReceive(&SPI1Handle, (unsigned char *)&data, (unsigned char *)&receive, 1, HAL_MAX_DELAY);

    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);

    return receive;
}

void MT6816_GetAngleData()
{
    unsigned short dataTx[2];
    unsigned short dataRx[2];
    unsigned char hCount;

    dataTx[0] = (0x80 | 0x03) << 8; // 0x8300
    dataTx[1] = (0x80 | 0x04) << 8; // 0x8400

    for (unsigned char i = 0; i < 3; i++) {
        // 读取 SPI 数据
        dataRx[0] = MT6816_SendAndRead16Bits(dataTx[0]);
        dataRx[1] = MT6816_SendAndRead16Bits(dataTx[1]);
        spiRawData.rawData = ((dataRx[0] & 0x00FF) << 8) | (dataRx[1] & 0x00FF);

        // 奇偶校验
        hCount = 0;
        for (unsigned char j = 0; j < 16; j++) {
            if (spiRawData.rawData & (0x0001 << j))
                hCount++;
        }
        if (hCount & 0x01) {
            spiRawData.checksumFlag = false;
        } else {
            spiRawData.checksumFlag = true;
            break;
        }
    }

    if (spiRawData.checksumFlag) {
        spiRawData.rawAngle = spiRawData.rawData >> 2;
        spiRawData.noMagFlag = (bool)(spiRawData.rawData & (0x0001 << 1));
    }
}

void MT6816_GetRawAngle()
{
    angleData.rawAngle = spiRawData.rawAngle;
}

void MT6816_GetRectifiedAngle()
{
    angleData.rectifiedAngle = readQuickCALData[angleData.rawAngle];
}

void MT6816_GetRectifiedState()
{
    // Check if the stored calibration data are valid
    angleData.rectifyValid = true;
    for (unsigned int i = 0; i < 16384; i++) {
        if (readQuickCALData[i] == 0xFFFF)
            angleData.rectifyValid = false;
    }
}
